<?php
/* 预约学车功能模块
 * 
 */
namespace Admin\Controller;

class AppointmentController extends ComController{
// 	预约学车列表页
	public function index(){

		$sc_id = session('uid');
		if($sc_id == ''){
			$this->error('您尚未登录，请登录',U('Login/index'));
		}else{
			//搜素
			$where = 'c.school_id ='. $sc_id;
		}
		//var_dump($where);die;

		if($_GET['field']=='user'){

			$where .= "  and  c.coach_name like '%{$_GET['keyword']}%' ";

		}

		if($_GET['field']=='phone'){

			$where .= "  and  c.phone like '%{$_GET['keyword']}%' ";

		}


		$prefix = C('DB_PREFIX');
		$p= intval($_GET['p'])?$_GET['p']:1;
		
		$pagesize = 15;#每页数量
		$offset = $pagesize * ($p - 1);//计算记录偏移量
		if($sc_id ==''){
			$this->error('您尚未登录，请登录',U('Login/index'));
		}else{
			
		}
		//查询预约教练基本信息
		$app_coach = M('appointment_coach');
		$count = $app_coach
		->alias('c')
		->join("{$prefix}license_type as t on c.li_type=t.id")
		->join("{$prefix}site as s on c.site_id=s.id")
		->join("{$prefix}car as ca on c.car_id=ca.id")
		->where($where)
		->field('c.*,t.type,s.site,ca.car_num')
		->count();
		
		$app_record = $app_coach
		->alias('c')
		->join("{$prefix}license_type as t on c.li_type=t.id")
		->join("{$prefix}site as s on c.site_id=s.id")
		->join("{$prefix}car as ca on c.car_id=ca.id")
		->join("{$prefix}coach as co on c.coach_id=co.id")
		->where($where)
		->order('add_time desc')
		->field('c.*,t.type,s.site,ca.car_num,co.name')
		->limit($offset . ',' . $pagesize)
		->select();//教练员的基本信息
		//查找排班日期
		$id = '';
		if(!empty($app_record)){
			foreach ($app_record as $key=>$val){
				if($id == ''){
					$id = $val['id'];
				}else{
					$id = $id. ','.$val['id'];
				}
			}
			//拿ID值去appointment_date 表中查询排班日期
			$app_date = M('appointment_date');
			$date = $app_date->distinct(true)->field('app_co_id,time')->where("app_co_id in ($id)")->select();
			$this->assign('site',$date);
		}
		//var_dump($date);
		//var_dump($app_record);die;
		$page = new \Think\Page($count, $pagesize);
		$page = $page->show();
		$this->assign('page',$page);
		$this->assign('date',$app_record);
		$this->display();
	}
	//排班详情
	public function detail(){
		$p= intval($_GET['p'])?$_GET['p']:1;
		$pagesize = 3;#每页数量
		$offset = $pagesize * ($p - 1);//计算记录偏移量
		$prefix = C('DB_PREFIX');
		//appointment_coach 表中的id值
		$id =I('get.id','','intval');
		$type = I('get.type')?I('get.type','','intval'):1;
		$app_coach = M('appointment_coach');
		$coachInfo = $app_coach
		->alias('c')
		->join("{$prefix}license_type as t on c.li_type=t.id")
		->join("{$prefix}site as s on c.site_id=s.id")
		->join("{$prefix}car as ca on c.car_id=ca.id")
		->where("c.id = $id")
		->field('c.*,t.type,s.site,ca.car_num')
		->find();//教练员的基本信息

		
		$app_date = M('appointment_date');
		
		$count1 = $app_date
		->where("app_co_id=$id")
		->order('time desc')
		->group('time')
		->select();
		$count = count($count1);
		if($type==2){
			$Info = $app_date
			->where("app_co_id=$id")
			->order('time desc')
			->group('time')
			->select();
		}else{
			$Info = $app_date
			->where("app_co_id=$id")
			->order('time desc')
			->limit($offset . ',' . $pagesize)
			->group('time')
			->select();
		}

		$time='';
		foreach ($Info as $k=>$v){
			if($time ==''){
				$time = $v['time'];
			}else{
				$time =$time. ','.$v['time'];
			}
		}
		

		$app_date_re = $app_date
		->where("app_co_id=$id and time in($time)")
		->order('time desc')
		->select();//预约日期
		

		if(!empty($app_date_re)){
			foreach ($app_date_re as $k=>$v){
				$app_time_id[]=$v['app_time_id'];
			}
			$app_time_id = array_unique($app_time_id);
			$app_time_id_arr= implode(',',$app_time_id);
			//根据 appointment_date 表中的app_time_id 去 appointment_time 表中查询时间段信息
			$app_time = M('appointment_time');
			$app_time_re = $app_time->where("id in ($app_time_id_arr)")->select();
			//var_dump($app_time_re);
			if(!empty($app_time_re)){
				foreach ($app_time_re as $key=>$val){
					$app_time_recod[$val['id']]=$val;//预约时间段
				}
				
				
				//将$app_date_re 中的time值 去重
				foreach ($app_date_re as $k=>$v){
					//$date= date('Y-m-d',$v['time']);
					$app_date_time[$v['app_co_id']][$v['time']][]=$app_time_recod[$v['app_time_id']];
				}

				
				
				//组合状态
				foreach ($app_date_re as $k=>$v){
						foreach ($app_date_time[$v['app_co_id']][$v['time']] as $key=>$val){
							if($v['app_time_id'] == $val['id']){
								$app_date_time[$v['app_co_id']][$v['time']][$key]['date_status']=$app_date_re[$k]['status'];
								$app_date_time[$v['app_co_id']][$v['time']][$key]['record_id']=$app_date_re[$k]['record_id'];
								$app_date_time[$v['app_co_id']][$v['time']][$key]['date_id']=$app_date_re[$k]['id'];
							}
						}
				}
				
				foreach ($app_date_time as $k=>$v){
					foreach ($v as $key=>$val){
						$app_date_t[]=array('date'=>$key,'time'=>$v[$key]);
					}
				}

			}else{
				//未查询到时间段信息
			}
		}else{
			//未查询到时间段记录
		}
		//var_dump($array);
		$page = new \Think\Page($count, $pagesize);
		$page = $page->show();
		$this->assign('page',$page);
		$this->assign('coachInfo',$coachInfo);
		$this->assign('date',$app_date_t);
		if($type ==2){
			$this->display('detail_pri');
		}else{
		$this->display();
		}
	}
	
//  添加预约学车
	public function add(){
		if(empty($_POST)){
			$this->display();
		}else{
			//dump($_POST);
			//写入 appointment_coach 表中的数据
			$data['school_id']= I('post.sc_id','','intval');//驾校id
			$data['coach_id']= I('post.coach_id','','intval');//教练id
 			$data['coach_name']= I('post.name','','strip_tags');//教练姓名
 			$data['phone']= I('post.phone','','strip_tags');//教练手机号
			$data['li_type']= I('post.li_type','','strip_tags');//驾考类型
			$data['site_id']= I('post.site','','intval');//场地id
			$data['course']= I('post.course','','intval');//科目类别
 			$data['car_id']= I('post.car_id','','strip_tags');//车牌号id
 			$data['category'] = I('post.category','','strip_tags');//练习模式 1普通，2模拟
			$data['add_time']=time();
			//dump($data);die;
			$time=I('post.time','','strip_tags');
			$slot_id=I('post.slot_id','','');//时间段id序列
			$app_coach = M('appointment_coach');
			$res = $app_coach->data($data)->add();
			if($res === false){
				$this->error('添加失败',U('Appointment/add'));
			}else{
				$app_co_id = $res;
				$timeArr =explode(',',$time);
				$array['add_time']=$data['add_time'];
				$array['school_id']=$data['school_id'];
				$array['city']=I('post.city','','intval');
				foreach ($timeArr as $k=>$v){
					$array['app_co_id']=$app_co_id;
					$array['time']=strtotime($v);
					foreach ($slot_id as $key=>$val){
						$array['app_time_id']=$val;
						$arr[]=$array;
					}
						
				}
				$app_date = M('appointment_date');
				$result = $app_date->addAll($arr);
				if($result === false){
					$app_coach->where("id = $app_co_id")->delete();
					$this->error('添加失败',U('Appointment/add'));
				}else{
					$this->success('添加成功',U('Appointment/index'));
				}
			}
		}
		
	}
	
	//取消排班
	public function cancel(){
		$id= I('get.date_id','','intval');//驾校id
		$url = $_SERVER['HTTP_REFERER']?$_SERVER['HTTP_REFERER']:U('Appointment/index');

		if(empty($id)){
				$this->error('参数错误，请重新选择',$url);
		}else{
			$sc_id = $_SESSION['uid'];
			if($sc_id == ''){
				$this->error('您尚未登录，请登录',U('Login/index'));
			}else{
				$app_date = M('appointment_date');
				$res = $app_date->where("id = $id and school_id = $sc_id")->find();
				if(isset($res)){
					$date['status']=0;
					$date['update_time']=time();
					$result = $app_date->where("id=$id")->save($date);
					if($result === false){
						$this->error('参数错误，请重新选择',$url);
					}else{
						$this->success('取消排班成功',$url);
					}
				}else{
					$this->error('参数错误，请重新选择',$url);
				}
			}
		}
	}
	
	//正常排班
	public function uncancel(){
		$id= I('get.date_id','','intval');//驾校id
		$url = $_SERVER['HTTP_REFERER']?$_SERVER['HTTP_REFERER']:U('Appointment/index');
	
		if(empty($id)){
			$this->error('参数错误，请重新选择',$url);
		}else{
			$sc_id = $_SESSION['uid'];
			if($sc_id == ''){
				$this->error('您尚未登录，请登录',U('Login/index'));
			}else{
				$app_date = M('appointment_date');
				$res = $app_date->where("id = $id and school_id = $sc_id")->find();
				if(isset($res)){
					$date['status']=1;
					$date['update_time']=time();
					$result = $app_date->where("id=$id")->save($date);
					if($result === false){
						$this->error('参数错误，请重新选择',$url);
					}else{
						$this->success('排班成功',$url);
					}
				}else{
					$this->error('参数错误，请重新选择',$url);
				}
			}
		}
	}
	

	
	/* ajax 调用接口 */
	//根据驾考类型，选择教练
	public function selectCoach(){
		//$data= I('post.license_type', '', 'intval');
		$sc_id = $_SESSION['uid'];
		if($sc_id == ''){
			echo json_encode(array('res'=>0,'msg'=>'您尚未登录','url'=>U('Login/index')));
		}else{
			$coach = M('coach');
			$data =$coach->where("d_id = $sc_id and status = 0")->select();
			if(!empty($data)){
				echo returnAjax($data);
			}else{
				echo json_encode(array('res'=>0,'msg'=>'您尚未添加教练员信息，请先添加教练员信息'));
			}

		}
		
	}
	//教练的详细信息
	public function  coachInfo(){
		$coach_id= I('post.coach_id', '', 'intval');
		//$coach_id=5;
		$coach = M('coach');
		$prefix = C('DB_PREFIX');
		$data =$coach->alias('c')
		->where("c.id = $coach_id")
		 ->join("{$prefix}member as m on c.d_id=m.uid")
		->field('c.id,c.d_id,c.name,c.driver_type,c.car_id,c.car_num,c.phone,m.city')
		->find();
		//print_r($coach->getLastSql());
		echo returnAjax($data);
	}
	//通过选取的科目类别，查找训练场地
	public function selectSite(){
		$course= I('post.course', '', 'intval');
		$sc_id = session('uid');
		if($sc_id == ''){echo json_encode(array('res'=>0,'msg'=>'您还没有登录，请登录','url'=>U('Login/index')));die;}
		$site = M('site');
		$data = $site->where("course = $course and school_id=$sc_id")->select();
		echo returnAjax($data);
		//print_r($course);
	}
	//从license_type 表中查找驾考类型
	public function liceseType(){
		$sc_id = session('uid');
		if($sc_id == ''){
			echo json_encode(array('res'=>0,'msg'=>'您尚未登录','url'=>U('Login/index')));
		}else{
			$type = M('license_type');
			$data = $type->field('id,type')->where("d_id = $sc_id")->select();
			echo returnAjax($data);
		}
	}
	//从car 表中查找车牌号
	public function carNum(){
		$sc_id = session('uid');
		$l_type = I('post.l_type','','intval');
		if($sc_id == ''){
			echo json_encode(array('res'=>0,'msg'=>'您尚未登录','url'=>U('Login/index')));
		}else{
			if($l_type == ''){
				echo json_encode(array('res'=>0,'msg'=>'参数错误，请重新选择'));
			}else{
				$type = M('car');
				$data = $type->where("d_id = $sc_id and l_type = $l_type")->select();
				echo returnAjax($data);
			}
			
		}
	}
//根据传过来的驾考类型，查找车辆信息
	public function changeCar(){
	$sc_id = session('school_id');
		$l_type = I('post.l_type','','intval');
		if($sc_id == ''){
			echo json_encode(array('res'=>0,'msg'=>'您尚未登录','url'=>U('Login/index')));
		}else{
			if($l_type == ''){
				echo json_encode(array('res'=>0,'msg'=>'参数错误，请重新选择'));
			}else{
				$type = M('car');
				$data = $type->where("d_id = $sc_id and l_type = $l_type")->select();
				echo returnAjax($data,'改驾考类型下暂无教练车信息');
			}
			
		}
		
	}

	//检验是否对教练重复排班
	public function checkCoach(){
		$prefix = C('DB_PREFIX');

		$cocah_id = I('post.coach_id','','intval');
		$time = I('post.time','','strip_tags');
		if($cocah_id == ''){
			echo json_encode(array('res'=>1,'msg'=>'未选择教练信息，请选择'));
		}
		if($time == ''){
			echo json_encode(array('res'=>1,'msg'=>'未选择排班日期，请选择'));
		}
		$timeArr =explode(',',$time);
		$time_s = '';
		foreach ($timeArr as $k=>$v){
			if($time_s == ''){
				$time_s = strtotime($v);
			}else{
				$time_s = $time_s.','.strtotime($v);
			}
		}
		$app_coach = M('appointment_coach');
		
		 $result = $app_coach->alias('c')
					->join("{$prefix}appointment_date as d on c.id = d.app_co_id")
					->where("c.coach_id = $cocah_id and d.time in ($time_s)")
					->field("d.app_co_id as co_id,d.time,d.status")
					->select(); 
		if(empty($result)){
			echo json_encode(array('res'=>0,'msg'=>'未重复排班'));
		}else{
			
			foreach ($result as $key=>$val){
				$cf_time[] =date('Y-m-d',$val['time']);
			}
			$cf_time = array_unique($cf_time);
			//将数组转为字符串
			$cf_str = implode(',', $cf_time);
			echo json_encode(array('res'=>2,'msg'=>"该教练已在{$cf_str}排班，是否重复排班"));
		}
	}
		
}